import { Context } from "koa";
import Joi from "joi";

import validate from "../libs/validate";
import { JsonResp, stats } from "../libs/stats";
import { ISession, IUser } from "../models/user";
import * as userService from "../services/user.service";


const sessions: ISession[] = [];

// 登陆
export async function login(ctx: Context){
  const data = validate(
    ctx.request.body,
    Joi.object({
      account: Joi.string().required(),
      password: Joi.string().required(),
    })
  );

  // 登陆成功后获取到session的id并通过set-cookie返回给客户端
  const sid = await userService.login(data);
  ctx.cookies.set('session_id', sid, {
    signed: true,
    expires: new Date(Date.now() + 1 * 24 * 3600 * 1000)        // 暂时将过期时间设置为1天
  })
  ctx.body = new JsonResp()
}

// 注册
export async function register(ctx: Context) {
  const data = validate(
    ctx.request.body,
    Joi.object({
      account: Joi.string()
        .min(3)
        .max(10)
        .required()
        .error(new Error("账号长度最少3位, 最多10位")),
      nickname: Joi.string()
        .min(1)
        .max(10)
        .required()
        .error(new Error("昵称长度最少1位, 最多10位")),
      password: Joi.string()
        .min(6)
        .max(10)
        .required()
        .error(new Error("密码长度最少6位, 最多10位")),
    })
  );

  const result = await userService.register(data);
  ctx.body = new JsonResp({
    _id: result
  });
}

// 退出登陆
export async function logout(ctx: Context){
  // 删除session_id的cookie
  const token = ctx.cookies.get("session_id");
  await userService.logout(token);
  ctx.cookies.set("session_id", "");
  ctx.body = new JsonResp();
}

// 获取用户信息
export async function info(ctx: Context){
  // 从cookie中取出session_id
  const token = ctx.cookies.get("session_id");
  console.log("info接口入参: " + token);
  // 通过数据库的会话记录找到关联的用户
  const user = await userService.getUserInfo(token);
  // 返回用户信息(password、salt不返回)
  ctx.body = new JsonResp(user);
}

// 修改密码
export async function changepwd(ctx: Context){
  const { oldPwd, password, confirmPwd } = validate(
    ctx.request.body,
    Joi.object({
      oldPwd: Joi.string()
        .min(6)
        .max(10)
        .required()
        .error(new Error("密码长度最少6位, 最多10位")),
      password: Joi.string()
        .min(6)
        .max(10)
        .required()
        .error(new Error("密码长度最少6位, 最多10位")),
      confirmPwd: Joi.string()
        .min(6)
        .max(10)
        .required()
        .error(new Error("密码长度最少6位, 最多10位")),
    })
  );

  const token = ctx.cookies.get("session_id");
  await userService.changePwd(token, oldPwd, password, confirmPwd);
  // 修改密码之后清空cookie
  ctx.cookies.set("session_id", "");
  ctx.body = new JsonResp();
}


